package graph.group.zhangtao.guider;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import graph.group.zhangtao.guider.getter.MediaGetterFactory;
import graph.group.zhangtao.guider.getter.TextGetterFactory;
import graph.group.zhangtao.guider.image.view.GuideFragment;
import graph.group.zhangtao.guider.image.view.viewpager.ModelPagerAdapter;
import graph.group.zhangtao.guider.image.view.viewpager.PagerModelManager;
import graph.group.zhangtao.guider.image.view.viewpager.ScrollerViewPager;
import graph.group.zhangtao.guider.image.view.viewpager.SpringIndicator;
import graph.group.zhangtao.guider.model.Content;
import graph.group.zhangtao.guider.model.ItemType;
import graph.group.zhangtao.guider.model.PositionType;
import graph.group.zhangtao.guider.model.ShowNode;
import graph.group.zhangtao.guider.model.ViewNode;
import graph.group.zhangtao.guider.utils.GetLocalFiles;
import graph.group.zhangtao.guider.utils.MySettingsAndTools;

public class NavigationActivity extends AppCompatActivity {

    private ScrollerViewPager viewPager;
    private MapView mMapView = null;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    public String getId() {
        return id;
    }

    private String id = "";
    //与选择无关，只是用来显示，请随意
    private int curr = 1;

    private List<ViewNode> currViewNodes;
    private ViewNode currViewNode;
    private NavigationActivity.ContentController contentController = null;
    private ListView listView;
    private DrawerLayout drawer;

    public static boolean isLocal() {
        return isLocal;
    }

    public static void setLocal(boolean local) {
        isLocal = local;
    }

    private static boolean isLocal = false;

//    private TextView textView;
//    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_navigation);

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();


        //获取id
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        isLocal = intent.getBooleanExtra("isLocal", false);
        if (isLocal) {
            Log.w("tao", "fromLocal");
        }
        //设置title
        setTitle(id);
        try {
            if (isLocal) {
                currViewNodes = ViewNode.getWithoutChildren(TextGetterFactory.textGet(this, GetLocalFiles.getFullDirPath(), id, "index.json", true));
            } else {
                currViewNodes = ViewNode.getWithoutChildren(TextGetterFactory.textGet(this, MySettingsAndTools.getSourcePath(), id, "index.json", false));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ViewNode first = ViewNode.getFirst(currViewNodes);
        currViewNode = first;
        //获取第一个
        processView(first);

        com.github.clans.fab.FloatingActionButton aPre = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.aPre);
        com.github.clans.fab.FloatingActionButton aNext = (com.github.clans.fab.FloatingActionButton) findViewById(R.id.aNext);
        aPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!currViewNode.getPid().equals("none")) {
                    ViewNode viewNode = ViewNode.search(currViewNode.getPid(), currViewNodes);
                    currViewNode = viewNode;
                    curr--;
                    processView(viewNode);

                } else {
                    Toast.makeText(NavigationActivity.this, "到头啦！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        aNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!currViewNode.getNid().equals("none")) {
                    ViewNode viewNode = ViewNode.search(currViewNode.getNid(), currViewNodes);
                    currViewNode = viewNode;
                    curr++;
                    processView(viewNode);

                } else {
                    Toast.makeText(NavigationActivity.this, "到头啦！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //地图比例尺初始化
        MapStatusUpdate u = MapStatusUpdateFactory.zoomTo(19);
        mMapView.getMap().animateMapStatus(u);

        listView = (ListView) findViewById(R.id.viewNode);
        initViewNode();
    }

    private void initViewNode() {
        List<String> title = new ArrayList<>();
        for (final ViewNode viewNode : currViewNodes) {
            String json = "";
            if (isLocal) {
                json = TextGetterFactory.textGet(this, GetLocalFiles.getFullDirPath(), id, viewNode.getId() + "/index.json", true);
            } else {
                json = TextGetterFactory.textGet(this, MySettingsAndTools.getSourcePath(), id, viewNode.getId() + "/index.json", false);
            }
            try {
                JSONObject jsonObject = new JSONObject(json);
                //类型
                String type = jsonObject.getString("positionType");
                //定位
                JSONObject locate = jsonObject.getJSONObject("locate");
                double getLatitude = locate.getDouble("getLatitude");
                double getLongitude = locate.getDouble("getLongitude");

//                setPosition(getLatitude, getLongitude);
//                //正文
                JSONObject text = jsonObject.getJSONObject("text");
                String tvArtTitle = text.getString("tvArtTitle");
//                //todo:背景图片
//                String ivArtBGImg = text.getString("ivArtBGImg");
//                setTitle(getTitleText() + "   " + PositionType.getChinese(type) + ":" + tvArtTitle);

                //打点
                //定义maker坐标点
                LatLng latLng = new LatLng(getLatitude, getLongitude);//初始画时候的经纬度
                //构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.location);
                //构建markerOption ,用于在地图上添加Marker
                OverlayOptions options = new MarkerOptions()
                        .position(latLng)//设置marker的位置
                        .icon(bitmap)    //设置marker的图标
                        .zIndex(9)       //设置marker所在的层级
                        .draggable(true);//设置手势的拖拽
                //在地图上添加Marker
                Marker marker = (Marker) mMapView.getMap().addOverlay(options);
                title.add(PositionType.getChinese(type) + ":" + tvArtTitle);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        final Object[] strs = title.toArray();
        listView.setAdapter(new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, strs));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("tao", String.valueOf(i));
                ViewNode viewNode1 = currViewNodes.get(i);
                curr = i + 1;
                currViewNode = viewNode1;
                processView(viewNode1);
                drawer.closeDrawers();
            }
        });
    }

    private void processView(ViewNode viewNode) {
        String json = "";
        if (isLocal) {
            json = TextGetterFactory.textGet(this, GetLocalFiles.getFullDirPath(), id, viewNode.getId() + "/index.json", true);
        } else {
            json = TextGetterFactory.textGet(this, MySettingsAndTools.getSourcePath(), id, viewNode.getId() + "/index.json", false);
        }
        try {
            JSONObject jsonObject = new JSONObject(json);
            //类型
            String type = jsonObject.getString("positionType");
            //定位
            JSONObject locate = jsonObject.getJSONObject("locate");
            double getLatitude = locate.getDouble("getLatitude");
            double getLongitude = locate.getDouble("getLongitude");
            setPosition(getLatitude, getLongitude);
            //正文
            JSONObject text = jsonObject.getJSONObject("text");
            String tvArtTitle = text.getString("tvArtTitle");
            //todo:背景图片
            String ivArtBGImg = text.getString("ivArtBGImg");
            setTitle(getTitleText() + "   " + PositionType.getChinese(type) + ":" + tvArtTitle);

            //contents，内容
            JSONArray contents = text.getJSONArray("contents");
            contentController = new NavigationActivity.ContentController(contents, viewNode.getId());

//            //打点
//            //定义maker坐标点
//            LatLng latLng = new LatLng(getLatitude, getLongitude);//初始画时候的经纬度
//            //构建Marker图标
//            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.location);
//            //构建markerOption ,用于在地图上添加Marker
//            OverlayOptions options = new MarkerOptions()
//                    .position(latLng)//设置marker的位置
//                    .icon(bitmap)    //设置marker的图标
//                    .zIndex(9)       //设置marker所在的层级
//                    .draggable(true);//设置手势的拖拽
//            //在地图上添加Marker
//            Marker marker = (Marker) mMapView.getMap().addOverlay(options);

        } catch (JSONException e) {
            e.printStackTrace();
            //todo:processView错误
            PagerModelManager manager = new PagerModelManager();
            manager.addCommonFragment(GuideFragment.class, getWrongBgRes(), getWrongTitles(), getWrongTexts());
            ModelPagerAdapter adapter = new ModelPagerAdapter(getSupportFragmentManager(), manager);
            viewPager.setAdapter(adapter);
            viewPager.fixScrollSpeed();
        }
    }

    private String getTitleText() {
        return id + "   " + String.valueOf(curr) + "/" + String.valueOf(currViewNodes.size());
    }

    public void setPosition(double latitude, double longitude) {
        BaiduMap baiduMap = mMapView.getMap();
        //设定中心点坐标
        LatLng cenpt = new LatLng(latitude, longitude);
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //返回地图状态
        baiduMap.setMapStatus(mMapStatusUpdate);
    }

    //地图生命周期
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    private List<String> getWrongTitles() {
        List<String> temp = new ArrayList<>();
        temp.add("1");
        return temp;
    }

    private List<CharSequence> getWrongTexts() {
        List<CharSequence> temp = new ArrayList<>();
        temp.add("1");
        return temp;
    }

    private List<String> getWrongBgRes() {
        String path1 = "http://zhangtao.group:8080/files/%E6%AD%A6%E5%A4%A7/1509003600594/1509003647311.jpg";
        List<String> temp = new ArrayList<>();
        temp.add(path1);
        return temp;
    }

    /**
     * 处理节点内的内容的方法
     */
    class ContentController {
        public static final String HASRECORDER = "HASRECORDER";
        public static final String NORECORDER = "NORECORDER";
        public static final String ISRECORDER = "ISRECORDER";

        private List<Content> contents;
        private Map<Integer, String> previousResult = new LinkedHashMap<>();
        private List<Integer> entryKey = new LinkedList<>();

        public List<ShowNode> getShowNodes() {
            return showNodes;
        }

        private List<ShowNode> showNodes = new LinkedList<>();
        private String mid;
        private String id = "";

        public ContentController(List<Content> contents, String mid) {
            this.contents = contents;
            this.mid = mid;
            try {
                this.id = URLEncoder.encode(NavigationActivity.this.getId(), "UTF-8") + "/";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            previousProcess();
            processEachContent(0);
        }

        public ContentController(JSONArray jsonArray, String mid) throws JSONException {
            contents = new LinkedList<>();
            this.mid = mid;
            try {
                this.id = URLEncoder.encode(NavigationActivity.this.getId(), "UTF-8") + "/";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                Content content = Content.processJsonObject(jsonArray.getJSONObject(i));
                contents.add(content);
            }
            previousProcess();
//            processEachContent(0);
            processAllContent();
        }

        private void previousProcess() {
            int myCursor = 0;
            while (myCursor < contents.size()) {
                Content content = contents.get(myCursor);
                //图片和文字检查下一个是不是音频
                if (content.getType().equals(ItemType.IMG) || content.equals(ItemType.TXT)) {
                    if (myCursor + 1 < contents.size() && (contents.get(myCursor + 1).getType().equals(ItemType.RECODER))) {
                        previousResult.put(myCursor, HASRECORDER);
                        entryKey.add(myCursor);
                        myCursor++;
                    } else {
                        previousResult.put(myCursor, NORECORDER);
                        entryKey.add(myCursor);
                    }
                }
                //音频
                else if (content.getType().equals(ItemType.RECODER)) {
                    previousResult.put(myCursor, ISRECORDER);
                    entryKey.add(myCursor);
                }
                //TODO：视频
                //视频和其他错误忽略
                else {

                }
                myCursor++;
            }
        }

//        public void processNext() {
//            if (cursor < entryKey.size()-1) {
//                cursor++;
//
//                int key = entryKey.get(cursor);
//                processEachContent(key);
//            }else {
//                Toast.makeText(NavigationActivity.this,"再翻也没有了啊！",Toast.LENGTH_SHORT).show();
//            }
//        }
//
//        public void processPre() {
//            if (cursor > 0) {
//                cursor--;
//                int key = entryKey.get(cursor);
//                processEachContent(key);
//            }else {
//                Toast.makeText(NavigationActivity.this,"再翻也没有了啊！",Toast.LENGTH_SHORT).show();
//            }
//        }

        private void processAllContent() {
            for (Integer integer : entryKey) {
                showNodes.add(processEachContent(integer));
            }
            List<String> bgRes = new LinkedList<>();
            List<CharSequence> titles = new LinkedList<>();
            List<String> count = new LinkedList<>();
            int i = 0;
            for (ShowNode showNode : showNodes) {
                i++;
                bgRes.add(showNode.getBgUrl());
                titles.add(showNode.getText());
                count.add(String.valueOf(i));
            }
            //初始化viewPager
            viewPager = (ScrollerViewPager) findViewById(R.id.view_pager);
//            viewPager.removeAllViews();
//        addBtns();
            SpringIndicator springIndicator = (SpringIndicator) findViewById(R.id.indicator);
            springIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                    Log.i("tao,", String.valueOf(position));
                }

                @Override
                public void onPageSelected(int position) {
//                    Log.i("tao,", String.valueOf(position));
                    ShowNode showNode = showNodes.get(position);
                    if (showNode.getShowType().equals(NavigationActivity.ContentController.HASRECORDER)
                            || showNode.getShowType().equals(NavigationActivity.ContentController.ISRECORDER)) {
                        actionOnRecorder(showNode);
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            PagerModelManager manager = new PagerModelManager();
            manager.addCommonFragment(GuideFragment.class, bgRes, count, titles);
            ModelPagerAdapter adapter = new ModelPagerAdapter(getSupportFragmentManager(), manager);
            viewPager.setAdapter(adapter);
            viewPager.fixScrollSpeed();

            // just set viewPager
            springIndicator.setViewPager(viewPager);

            //init第一个图片
            ShowNode showNode = showNodes.get(0);
            if (showNode.getShowType().equals(NavigationActivity.ContentController.HASRECORDER)
                    || showNode.getShowType().equals(NavigationActivity.ContentController.ISRECORDER)) {
                actionOnRecorder(showNode);
            }
        }

        private void actionOnRecorder(ShowNode showNode) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            if (isLocal) {
                new MediaGetterFactory(showNode.getRecorderUrl(), mediaPlayer, true);
            } else {
                new MediaGetterFactory(showNode.getRecorderUrl(), mediaPlayer, false);
            }
//            try {
//                mediaPlayer.prepare();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            mediaPlayer.start();
        }

        private ShowNode processEachContent(int key) {
            //todo:local
            ShowNode showNode = new ShowNode();
            String type = previousResult.get(key);
            if (type.equals(HASRECORDER)) {
                showNode.setShowType(NavigationActivity.ContentController.HASRECORDER);
                Content content = contents.get(key);
                if (!content.getContent().equals("null")) {
//                    textView.setText(content.getContent());
//                    mContent = content.getContent();
                    showNode.setText(content.getContent());
                    showNode.setTextType(content.getStyle());
                } else {
                    showNode.setText(MySettingsAndTools.getNOCONTENT());
                }
                if (!content.getUrl().equals("null")) {
//                    ImageGetter.setImageView(
//                            NavigationActivity.this,
//                            imageView,
//                            MySettingsAndTools.getSourcePath(),
//                            id,
//                            mid + "/" + content.getUrl());
                    if (isLocal) {
                        showNode.setBgUrl(GetLocalFiles.getFullDirPath() +
                                NavigationActivity.this.getId() + "/" +
                                mid + "/" + content.getUrl());
                    } else {
                        showNode.setBgUrl(MySettingsAndTools.getSourcePath() +
                                id +
                                mid + "/" + content.getUrl());
                    }
                } else {
                    showNode.setBgUrl(MySettingsAndTools.getNOPICTURE());
                }

                Content recorder = contents.get(key + 1);
//                MediaGetterFactory mediaGetter = new MediaGetterFactory(
//                        NavigationActivity.this,
//                        MySettingsAndTools.getSourcePath(),
//                        id,
//                        mid + "/" + recorder.getUrl(),
//                        new MediaPlayer());
//                mediaGetter.play();
                if (isLocal) {
                    showNode.setRecorderUrl(
                            GetLocalFiles.getFullDirPath() +
                                    NavigationActivity.this.getId() + "/" +
                                    mid + "/" + recorder.getUrl()
                    );
                } else {
                    showNode.setRecorderUrl(
                            MySettingsAndTools.getSourcePath() +
                                    id +
                                    mid + "/" + recorder.getUrl()
                    );
                }
            } else if (type.equals(NORECORDER)) {
                showNode.setShowType(NavigationActivity.ContentController.NORECORDER);
                Content content = contents.get(key);
                if (!content.getContent().equals("null")) {
//                    textView.setText(content.getContent());
//                    mContent = content.getContent();
                    showNode.setText(content.getContent());
                    showNode.setTextType(content.getStyle());
                } else {
                    showNode.setText(MySettingsAndTools.getNOCONTENT());
                }
                if (!content.getUrl().equals("null")) {
//                    ImageGetter.setImageView(
//                            NavigationActivity.this,
//                            imageView,
//                            MySettingsAndTools.getSourcePath(),
//                            id,
//                            mid + "/" + content.getUrl());
                    if (isLocal) {
                        showNode.setBgUrl(GetLocalFiles.getFullDirPath() +
                                NavigationActivity.this.getId() + "/" +
                                mid + "/" + content.getUrl());
                    } else {
                        showNode.setBgUrl(MySettingsAndTools.getSourcePath() +
                                id +
                                mid + "/" + content.getUrl());
                    }
                } else {
                    showNode.setBgUrl(MySettingsAndTools.getNOPICTURE());
                }
            } else if (type.equals(ISRECORDER)) {
                showNode.setShowType(NavigationActivity.ContentController.ISRECORDER);
                Content recorder = contents.get(key);
                if (!recorder.getContent().equals("null")) {
                    showNode.setText(recorder.getContent());
                    showNode.setTextType(recorder.getStyle());
                } else {
                    showNode.setText(MySettingsAndTools.getNOCONTENT());
                }
                showNode.setBgUrl(MySettingsAndTools.getNOPICTURE());
                if (isLocal) {
                    showNode.setRecorderUrl(
                            GetLocalFiles.getFullDirPath() +
                                    NavigationActivity.this.getId() + "/" +
                                    mid + "/" + recorder.getUrl()
                    );
                } else {
                    showNode.setRecorderUrl(
                            MySettingsAndTools.getSourcePath() +
                                    id +
                                    mid + "/" + recorder.getUrl()
                    );
                }
            } else {
                showNode.setShowType(MySettingsAndTools.getWRONG());
            }
            return showNode;
        }


        public List<Content> getContents() {
            return contents;
        }

    }

    //侧边栏状态
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.navigation, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}
